package com.ichir.projects.uiflow.internal.factories;

import java.util.HashMap;
import java.util.Map;

import com.ichir.projects.uiflow.ApplicationContext;
import com.ichir.projects.uiflow.definition.ICashable;
import com.ichir.projects.uiflow.definition.IFlowPart;
import com.ichir.projects.uiflow.ui.api.IUiPart;
import com.ichir.projects.uiflow.ui.api.IUiView;

public class UiViewFactory extends UiPartFactory {

	private Map<Class<? extends IUiPart>, IUiPart> cash = new HashMap<Class<? extends IUiPart>, IUiPart>();

	@Override
	protected IUiPart getPart(IFlowPart flowPart, ApplicationContext context,
			Map<String, Object> attributes) throws Exception {
		
		Class<? extends IUiPart> forName = flowPart.getUiPartClassname();
		// get from cash?
		if (cash.containsKey(forName)) {
			System.out.println(">> get from cash "+forName);
			return cash.get(forName);
		} else {
			IUiView uiPart;
			// new instance
			System.out.println(">> new instance of "+forName);
			uiPart = (IUiView) forName.newInstance();
			// initialize view
			((IUiView) uiPart).initializeView(context, attributes);
			// put view into cash
			if (flowPart instanceof ICashable) {
				if (((ICashable) flowPart).cash()) {
					System.out.println(">> cash view "+forName);
					cash.put(forName, uiPart);
				}
			}
			return uiPart;
		}
	}

}
